<?php

namespace App\Api\Controllers;

use Common\ApiController;
use Common\Common;
use Common\Models\FUserInfo;
use Common\Models\FUsers;
use Common\Models\FUsersExtend;
use Common\Models\User;

class RelationtaokeController extends ApiController
{
    protected $params;

    public function initialize()
    {
        $this->params = array_merge($this->request->get(), $this->request->getPost());
    }

    public function taobao_relationAction(){
        $params = $this->params;
        if(!isset($params['code']) || empty($params['code'])){
            $msg="没有淘宝授权code码";
            $this->return_url(-1,$msg);
        }
        if(!isset($params['state']) || empty($params['state'])){
            $msg="state参数没有";
            $this->return_url(-1,$msg);
        }
        $params = [
            'client_id'=>$this->config->services->union->tbUnion->appKey,
            'client_secret'=>$this->config->services->union->tbUnion->appSecret,
            'grant_type'=>'authorization_code',
            'code'=>$params['code'],
            'redirect_uri'=>$this->config->services->union->tbUnion->tbCallBack,
            'view'=>'wap',
            'state'=>$params['state'],
            'method'=>'taobao.top.auth.token.create',
        ];
        $res=$this->taobao->get_token($params);
        if(isset($res['error_response'])){
            $error=$res['error_response']['sub_msg'];
            $this->return_url(-1,$error);
        }
        if(isset($res['status']) && $res['status']==false){
            $this->return_url(-1,$res['msg']);
        }
        $userExtends = new FUsersExtend();
        $is_set=$userExtends->findFirstByTbRid($res['data']['tb_rid']);
        if($is_set){
            $UserDb = new User();
            $user = $UserDb->findFirstById($is_set->user_id);
            if($user){
                $user = $user->toarray();
                $phone=substr_replace($user['phone'],'****',3,4);
            }
            $msg="此淘宝授权已被手机{$phone}占用 请解绑后再重新授权";
            $this->return_url(-1,$msg);
        }
        $user_data = $userExtends->findFirstByUserId($params['state']);
        $user_data->tb_name = $res['data']['tb_nickname'];
        $user_data->tb_rid = $res['data']['tb_rid'];
        $user_data->tb_special_id = $res['data']['special_id'];
        if($user_data->save()){
            $this->return_url(1,'授权成功',$user_data->tb_rid);
        }
    }


    /*
     * 跳转地址 回调
     *
     */
    public function return_url($wo=-1,$msg='',$rid=''){
        //$domain = Common::domain();
        $url = Common::domain()."/api/h5page/relationtaobao?wo={$wo}&msg={$msg}&rid=$rid";
        Header("Location:$url");
        die();
    }

}
